var constantData = require('constant_data.js')
var util = require('../utils/util.js');

function locationAddr(callback, errback) {
  // let locationStat = true
  // wx.startLocationUpdate({
  //   type: 'wgs84',
  //   success: function (res) {
  //     console.log('获取位置信息-----1',res)
  //     wx.onLocationChange((res)=>{  
  //       // console.log('获取位置信息2',res)      
  //       wx.setStorageSync('location', res)
  //       if (locationStat && callback) {
  //         locationStat = false
  //         callback(res);
  //       }
  //     })      
  //   },
  //   fail: function (err) {
  //     console.log("错误获取地址位置", err)
  //     if(locationStat && errback) {
  //       locationStat = false
  //       errback(err)
  //     }
  //   }
  // })
}
function locationCallback(locationInfo, that) {
  var latitude = locationInfo.latitude;
  var longitude = locationInfo.longitude;
  that.setData({
    longitude: locationInfo.longitude
    , latitude: locationInfo.latitude
    , markers: [
      {
        id: 0
        , iconPath: "../../image/marker_red_sprite.png"
        , longitude: locationInfo.longitude
        , latitude: locationInfo.latitude
        , width: 39
        , height: 25
      }
    ]
  })
}

function debugInfo(data, header) {
  try {

    wx.request({
      url: constantData.CONSTATNT_DATA.BASE_URL + '/log/lease_debug',
      header: header,
      data: data,
      success: function (res) {

      }
    })

  } catch (e) {
    console.error("*******>record debug error<******", e)
  }

}


//记录程序的错误信息
function recordErrorInfo(errType, errDesc, homingPileBlueName = '') {

  console.log("记录错误日志到服务器...")

  var systemInfo = wx.getStorageSync('systeminfo')
  var miniVer = constantData.CONSTATNT_DATA.MINI_VERSION;
  let nowTime = util.formatTime(new Date()) + ',';
  getApp().executeRequest(function (header) {
    wx.request({
      url: constantData.CONSTATNT_DATA.BASE_URL + '/lease/error/bc',
      method: 'post',      
      header: header,
      data: {
        homingPileBlueName: homingPileBlueName,
        phoneOs: systemInfo.system,//手机系统信息,最长245
        phoneFactory: systemInfo.model,//手机厂商,最长245
        phoneType: systemInfo.model,//手机型号,最长245
        weixinVer: systemInfo.version + ',' + systemInfo.SDKVersion + ',' + miniVer,//微信版本号,最长45
        errType: parseInt((errType + '').replace(/[^0-9]/ig, '')),//错误类型,最大值127；1.搜索,2.连接,3.auth,4.init 5. 95 6. 85
        errDesc: nowTime + errDesc,//错误描述,最长545
      },
      success: function (res) {
        console.log("蓝牙连接错误日志记录成功")
        console.log(res)
      },
      fail: function (res) {
        console.log("蓝牙连接错误日志记录失败")
        console.log(res)
      }
    })
  })


}

function compareVersion(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i])
    const num2 = parseInt(v2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }

  return 0
}


function storeGatewayClientType() {
  var app = getApp();
  let wxType = 'wxmini_gateway';
  app.globalData.loginData.wxctype  = wxType;
  if (app.globalData._that && app.globalData._that.data.hpIsColony > 0) {
    wx.setStorageSync('wxctype', wxType);
  }
}
function storeWxClientType(that) {
  if (that) {
    that.data.isColonyCon = false;
  }
  let wxType = 'wxmini';
  getApp().globalData.loginData.wxctype  = wxType;
  wx.setStorageSync('wxctype', wxType);
}
var timerCount = null;
function conTimeCountSeconds(that) {
  console.log("连接倒计时定时器--->");
  that.setData({
    conLeftSeconds: 60
  });
  clearInterval(timerCount);

  timerCount =setInterval(()=>{
    console.log("connect statrt count second -->", that.data.conLeftSeconds);
    let leftSecond = that.data.conLeftSeconds - 1;
    console.log("connnect -->leftSecond=", leftSecond, timerCount);
    if (leftSecond <= 0) {
      that.setData({
        loading_show: false
      });
      clearInterval(timerCount);
    } else {
      that.setData({
        conLeftSeconds: leftSecond
      });
    }
  },1000);
    
}

function clearConTimeCountTimer(num) {
  console.log("连接倒计时定时器关闭---a>", num, timerCount)
  clearInterval(timerCount);
}

function isJSON(str) {
  if (typeof str == 'string') {
      try {
          var obj = JSON.parse(str);
          if(typeof obj == 'object' && obj ){
              return true;
          }else{
              return false;
          }
      } catch(e) {
          console.log('error：'+str+'!!!'+e);
          return false;
      }
  }
  console.log('It is not a string!')
}


module.exports.locationAddr = locationAddr
exports.locationCallback = locationCallback
exports.debugInfo = debugInfo
exports.recordErrorInfo = recordErrorInfo
exports.compareVersion = compareVersion
exports.storeGatewayClientType = storeGatewayClientType
exports.storeWxClientType = storeWxClientType
exports.conTimeCountSeconds = conTimeCountSeconds
exports.clearConTimeCountTimer = clearConTimeCountTimer
exports.isJSON = isJSON
